package com.sa.token.exception;


import com.sa.token.message.StandardResponse;
import com.sa.token.utils.SystemLogUtil;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @desc: 全局日志切面, 拦截所有controller请求，写入日志
 * @projectName: sa-token-serve
 * @author: xhs
 * @date: 2021/12/31 14:45
 * @version: JDK 1.8
 */
@Slf4j
@Aspect
@Component
public class GlobalAspect {

    /**
     * 定义AOP签名,拦截的文件
     */
    @Pointcut("execution(public * com.sa.token.controller..*.*(..))")
    public void systemLog1() {
    }

    /**
     * 定义AOP签名,排除拦截
     */
    @Pointcut("execution(public * com.sa.token.controller.LogController.*(..))")
    public void systemLog2() {
    }

    /**
     * 定义AOP签名,排除拦截
     */
    @Pointcut("execution(public * com.sa.token.controller.LoginController.*(..))")
    public void systemLog3() {
    }

    /**
     * 定义AOP签名,排除拦截
     */
    @Pointcut("systemLog1() && !systemLog2() && !systemLog3()")
    public void systemLog() {
    }

    /**
     * 环绕通知,环绕增强，相当于MethodInterceptor
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("systemLog()")
    public Object surround(ProceedingJoinPoint pjp) throws Throwable {
        log.info("---请求：{}---", pjp.proceed());
        SystemLogUtil.startRequest();
        Object proceed = pjp.proceed();
        // 如果是 AjaxJson
        if (proceed instanceof StandardResponse) {
            SystemLogUtil.endRequest((StandardResponse) proceed);
        } else if (proceed instanceof String) {
            // 如果是 String
            SystemLogUtil.endRequest(StandardResponse.success(String.valueOf(proceed)));
        }
        // 如果都不是
        else {
            SystemLogUtil.endRequest(StandardResponse.success(String.valueOf(proceed)));
        }
        return proceed;
    }

}
